package com.wangyadong.hobby.common.utils;

import com.wangyadong.hobby.front.model.WuserInfo;
import com.wangyadong.hobby.common.utils.ConfigurableApplitionUtil;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Date;

/**
 * @ClassName BaseControllerConfig
 * @Description TODO
 * @Authpr Antonio
 * @Data 2018-07-03 9:58
 */
@Configuration
@ComponentScan
public class BaseControllerConfig {

    String COOKIE = "WANGZHIXING";
    String COOKIE_TIMR = "WANGZHIXING_TIME";


    protected String getFrontMessage() {
        return "";
    }


    protected void setCookieWithSession(HttpSession session, WuserInfo wuserInfo) {
        wuserInfo.setPassword("");
        session.setAttribute(COOKIE, wuserInfo);
        session.setAttribute(COOKIE_TIMR, new Date());
    }

    public WuserInfo getSession(HttpSession session) {
        return (WuserInfo) session.getAttribute(COOKIE);
    }

    /**
     * @param cookies
     * @param name
     * @return cookie
     */
    public Cookie getCookie(Cookie[] cookies, String name) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(name)) {
                return cookie;
            }
        }
        return null;
    }

    /**
     * @param response
     * @param name
     * @param value
     * @param expiry
     * @param domain
     * @return cookie
     */
    public Cookie addCookie(HttpServletResponse response, String name, String value, Integer expiry
    ) throws UnsupportedEncodingException {
        Cookie cookie = new Cookie(URLEncoder.encode(name, "UTF-8"), value);
        cookie.setMaxAge(expiry);
        response.addCookie(cookie);
        return cookie;
    }

    /**
     * @param response
     * @param name
     */
    public void cancleCookie(HttpServletResponse response, String name) throws UnsupportedEncodingException {
        Cookie cookie = new Cookie(URLEncoder.encode(name, "UTF-8"), null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    public String getDiskPath() {
        return ConfigurableApplitionUtil.getProperty("save-file-path");
    }


    public boolean isEmtpyNullBlank(Object object, String message, String str) {
        if (null == object) {
            message = str;
            return true;
        }
        if (object instanceof Collection) {
            if (((Collection) object).isEmpty()) {
                message = str;
                return true;
            }
            return false;
        }
        if (object instanceof String) {
            if ("".equals(object)) {
                message = str;
                return true;
            }
        }
        return false;
    }


}
